/*
 * Copyright (c) 2024 Termony Co., Ltd. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "hdf_vuart.h"
#include "osal_mem.h"
#include "osal_irq.h"
#include "hdf_base.h"
#include "hdf_log.h"

#ifdef LOG_TAG
#undef LOG_TAG
#endif
#define LOG_TAG "VUART_INTR"

static void HDF_VuartRxCmpl(const uint8_t *data, size_t len, struct VuartCb *vuartCb)
{
    struct VuartDataItem *dataItem = \
        (struct VuartDataItem *)OsalMemCalloc(sizeof(struct VuartDataItem) + len);
    if (dataItem == NULL) {
        HDF_LOGE("%s: OsalMemCalloc is failed.", __func__);
        return;
    }

    uint8_t *buffer = ((uint8_t *)dataItem) + sizeof(struct VuartDataItem);
    (void)memcpy_s(buffer, len, data, len);
    dataItem->size = len;
    dataItem->used = len;

    OsalMutexLock(&(vuartCb->rxMux));
    DListInsertTail(&(dataItem->list), &(vuartCb->recv));
    OsalMutexUnlock(&(vuartCb->rxMux));

    HDF_VuartServiceRequest(vuartCb, UART_IO_READ, len);
}

int32_t HDF_VuartIsrRegister(struct VuartCb *vuartCb)
{
    openamp_vuart_rxcmpl_callback_register(HDF_VuartRxCmpl, vuartCb);
    return HDF_SUCCESS;
}

int32_t HDF_VuartIsrUnregister(struct VuartCb *vuartCb)
{
    return HDF_SUCCESS;
}